package com.qu.waibao.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMKit;
import com.baidu.location.BDLocation;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.qu.waibao.AppConfig;
import com.qu.waibao.MyApplication;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.baidu.openim.SystemActivity;
import com.qu.waibao.base.BaseFragment;
import com.qu.waibao.base.BaseRecyclerAdapter;
import com.qu.waibao.bean.HomeBean;
import com.qu.waibao.bean.Image;
import com.qu.waibao.home.activity.CallActivity;
import com.qu.waibao.home.activity.ChouActivity;
import com.qu.waibao.home.activity.KefuActivity;
import com.qu.waibao.home.activity.OtherServiceActivity;
import com.qu.waibao.home.activity.PickCityActivity;
import com.qu.waibao.home.activity.PublishDetailActivity;
import com.qu.waibao.home.activity.ShopActivity;
import com.qu.waibao.home.activity.WebActivity;
import com.qu.waibao.home.adpater.CallAdapter;
import com.qu.waibao.home.adpater.KefuAdapter;
import com.qu.waibao.home.adpater.PublishAdapter;
import com.qu.waibao.home.adpater.ServiceAdapter;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.activity.AcceptOrderActivity;
import com.qu.waibao.my.activity.HelpDetailActivity;
import com.qu.waibao.my.activity.HexiaoActivity;
import com.qu.waibao.my.activity.PublishOrderActivity;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.search.SearchActivity;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.TDevice;
import com.qu.waibao.utils.ToastUtil;
import com.qu.waibao.widget.CustomPopupWindow;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * Created by quguangle on 2018/7/21.
 * emial 1123599561@qq.com
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener,LocationUtils.ILocateDelegate{
    @BindView(R.id.publish_recycler)
    public RecyclerView publish_recycler;
    @BindView(R.id.call_recycler)
    public RecyclerView call_recycler;
    @BindView(R.id.fuwu_recycler)
    public RecyclerView fuwu_recycler;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.ll_chexiao)
    LinearLayout ll_chexiao;
    @BindView(R.id.ll_shop)
    LinearLayout ll_shop;
    @BindView(R.id.ll_publish_order)
    LinearLayout ll_publish_order;
    @BindView(R.id.tv_call)
    TextView tv_call;
    @BindView(R.id.tv_finishing)
    TextView tv_finishing;
    @BindView(R.id.iv_call)
    ImageView iv_call;
    @BindView(R.id.iv_fuwu)
    ImageView iv_fuwu;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.tv_qiandao)
    TextView tv_qiandao;
    @BindView(R.id.tv_one)
    TextView tv_one;
    @BindView(R.id.tv_dingdan)
    TextView tv_dingdan;
    @BindView(R.id.tv_two)
    TextView tv_two;
    private PublishAdapter adapter;
    private CallAdapter callAdapter;
    private ServiceAdapter serviceAdapter;
    private Intent intent;
    private int card = 0;
    private String latitude = "";
    private String longitude = "";
    private HomeBean homeBean = null;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        LocationUtils.locateDelegateArrayList.add(this);
        card = AppConfig.getInt("card");
        if(card == 1){ //车主
            ll_chexiao.setVisibility(View.GONE);
        }else if(card == 2){ //修理工
            ll_chexiao.setVisibility(View.GONE);
            ll_publish_order.setVisibility(View.GONE);
            tv_call.setText("待完成");
            tv_finishing.setText("待抢单");
            iv_call.setImageResource(R.drawable.sy_qitafuwu);
            iv_fuwu.setImageResource(R.drawable.sy_lansedianhua);
        }else if(card == 3){ //商家
            tv_call.setText("待完成");
            tv_finishing.setText("待抢单");
            iv_call.setImageResource(R.drawable.sy_qitafuwu);
            iv_fuwu.setImageResource(R.drawable.sy_lansedianhua);
        }
        initBanner();
    }

    @Override
    protected void initData() {
        super.initData();
        //我的发布
        adapter = new PublishAdapter(mContext,BaseRecyclerAdapter.NEITHER);
        LinearLayoutManager publish_manager = new LinearLayoutManager(mContext);
        publish_recycler.setLayoutManager(publish_manager);
        publish_recycler.setHasFixedSize(true);
        publish_recycler.setNestedScrollingEnabled(false);
        publish_recycler.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, long itemId) {
                String serviceid = adapter.getItems().get(position).getServiceid();
                Intent intent = new Intent(mContext, PublishDetailActivity.class);
                intent.putExtra("serviceid",serviceid);
                startActivity(intent);
            }
        });
        //一键呼叫
        callAdapter = new CallAdapter(mContext, BaseRecyclerAdapter.NEITHER);
        LinearLayoutManager call_manager = new LinearLayoutManager(mContext);
        call_recycler.setLayoutManager(call_manager);
        call_recycler.setHasFixedSize(true);
        call_recycler.setNestedScrollingEnabled(false);
        call_recycler.setAdapter(callAdapter);
        callAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, long itemId) {
                String serviceid = callAdapter.getItems().get(position).getServiceid();
                Intent intent = new Intent(mContext, PublishDetailActivity.class);
                intent.putExtra("serviceid",serviceid);
                startActivity(intent);
            }
        });

        //其他服务
        serviceAdapter = new ServiceAdapter(mContext, BaseRecyclerAdapter.NEITHER);
        LinearLayoutManager service_manager = new LinearLayoutManager(mContext);
        fuwu_recycler.setLayoutManager(service_manager);
        fuwu_recycler.setHasFixedSize(true);
        fuwu_recycler.setNestedScrollingEnabled(false);
        fuwu_recycler.setAdapter(serviceAdapter);
        serviceAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, long itemId) {
                String serviceid = serviceAdapter.getItems().get(position).getServiceid();
                Intent intent = new Intent(mContext, PublishDetailActivity.class);
                intent.putExtra("serviceid",serviceid);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if(LocationUtils.Mylocation != null){
             longitude = String.valueOf(LocationUtils.Mylocation.getLongitude());
             latitude = String.valueOf(LocationUtils.Mylocation.getLatitude());
             tv_location.setText(LocationUtils.Mylocation.getCity().substring(0,2));
        }else {
            LocationUtils.startLocation();
        }
        getHomeData();
    }


    public void initBanner(){
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if(homeBean != null) {
                    String textInfoid = homeBean.getBanner().get(position).getTextInfoid();
                    Intent intent = new Intent(mContext, HelpDetailActivity.class);
                    intent.putExtra("textInfoid", textInfoid);
                    startActivity(intent);
                }
            }
        });
    }

    @OnClick({R.id.ll_call,R.id.ll_fuwu,R.id.ll_news,R.id.ll_shop,R.id.iv_phone,R.id.ll_chexiao,R.id.tv_search,
    R.id.tv_publish_more,R.id.tv_service_more,R.id.tv_call_more,R.id.ll_qian,R.id.ll_chou,R.id.rl_warning,
            R.id.tv_location})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_warning: //系统消息
               //startActivity(new Intent(mContext, SystemActivity.class));
                intent = new Intent(mContext, ChouActivity.class);
                intent.putExtra("title","系统消息");
                startActivity(intent);
                break;
            case R.id.et_search:
                intent = new Intent(mContext, SearchActivity.class);
                intent.putExtra("type",0);
                startActivity(intent);
                break;
            case R.id.ll_qian:
                intent = new Intent(mContext, WebActivity.class);
                intent.putExtra("title","签到");
                startActivity(intent);
                break;
            case R.id.ll_chou:
                intent = new Intent(mContext, ChouActivity.class);
                intent.putExtra("title","抽奖");
                startActivity(intent);
                break;
            case R.id.tv_publish_more:
                startActivity(new Intent(mContext, PublishOrderActivity.class));
                break;
            case R.id.tv_location:
                startActivityForResult(new Intent(mContext, PickCityActivity.class),0);
                break;
            case R.id.tv_service_more: //查看更多
                intent = new Intent(mContext, OtherServiceActivity.class);
                intent.putExtra("flag",2);
                startActivity(intent);
                break;
            case R.id.tv_call_more:
                if(card == 2 || card == 3){ //修理工(商家)---待完成
                    intent = new Intent(mContext, AcceptOrderActivity.class);
                    intent.putExtra("type","finishing");
                }else if(card == 1){
                    intent = new Intent(mContext, CallActivity.class);
                }
                startActivity(intent);
                break;
            case R.id.ll_call:
                startActivity(new Intent(mContext, CallActivity.class));
                break;
            case R.id.ll_fuwu:
                intent = new Intent(mContext, OtherServiceActivity.class);
                intent.putExtra("flag",1);
                startActivity(intent);
                break;
            case R.id.ll_news:
                startActivity(new Intent(mContext,KefuActivity.class));
                break;
            case R.id.tv_search:
                startActivity(new Intent(getActivity(),SearchActivity.class));
                break;
            case R.id.ll_chexiao:
                startActivity(new Intent(mContext, HexiaoActivity.class));
                break;
            case R.id.ll_shop:
                startActivity(new Intent(mContext, ShopActivity.class));
                break;
            case R.id.iv_phone:
                if(homeBean == null){
                    return;
                }
                NiceDialog.init()
                        .setLayoutId(R.layout.kefu_popuwindow_layout)     //设置dialog布局文件
                        .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                            @Override
                            public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                                final KefuAdapter adapter = new KefuAdapter(mContext,BaseRecyclerAdapter.NEITHER);
                                RecyclerView recyclerView = holder.getView(R.id.recyclerView);
                                LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
                                recyclerView.setLayoutManager(layoutManager);
                                recyclerView.setHasFixedSize(true);
                                recyclerView.setNestedScrollingEnabled(false);
                                recyclerView.setAdapter(adapter);
                                if(adapter.getItems().size() == 0){
                                    adapter.clear();
                                    adapter.addAll(homeBean.getServicephone());
                                }
                                adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(int position, long itemId) {
                                        String phone = adapter.getItems().get(position).getJianjie();
                                         if(ContextCompat.checkSelfPermission(mContext,Manifest.permission.CALL_PHONE)
                                                 == PackageManager.PERMISSION_GRANTED){
                                             TDevice.openDial(mContext,phone);
                                         }else {
                                             ToastUtil.show(mContext,"您还没有打电话的权限，请到设置界面开启");
                                         }
                                    }
                                });
                            }
                        })
                        .setMargin(16)
                        .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                        .setShowBottom(false)     //是否在底部显示dialog，默认flase
                        .setOutCancel(true)     //点击dialog外是否可取消，默认true
                        .show(getChildFragmentManager());     //显示dialog
                break;
        }
    }

    @Override
    public void onLocateSuccess(BDLocation location) {

    }

    @Override
    public void onLocateFailed() {

    }

    public class GlideImageLoader extends ImageLoader {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            HomeBean.BannerBean bean = (HomeBean.BannerBean) path;
            Glide.with(context).load(NetManager.getFullUrl(bean.getPhoto())).into(imageView);
        }
    }

    public void getHomeData(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.homepage_get);
        map.put("userid",AppConfig.getString("userid"));
        map.put("versionvalue", TDevice.getVersionCode()+"");
        map.put("latitude",latitude);
        map.put("longitude",longitude);
        NetManager.getInstance().request(getActivity(), map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                homeBean = GsonUtil.createGson().fromJson(result,HomeBean.class);
                if(homeBean != null) {
                    AppConfig.saveString("share",homeBean.getUrl_share());
                    // banner
                    banner.setImages(homeBean.getBanner());
                    banner.start();
                    //提醒
                    if(homeBean.getMessage().size() > 0) {
                        if(homeBean.getMessage().size() == 1){
                            tv_qiandao.setText(homeBean.getMessage().get(0).getRemark());
                            tv_one.setText(homeBean.getMessage().get(0).getCreatedate());
                        }else if(homeBean.getMessage().size() == 2){
                            tv_qiandao.setText(homeBean.getMessage().get(0).getRemark());
                            tv_one.setText(homeBean.getMessage().get(0).getCreatedate());
                            tv_dingdan.setText(homeBean.getMessage().get(1).getRemark());
                            tv_two.setText(homeBean.getMessage().get(1).getCreatedate());
                        }
                    }
                    // 我的发布(车主)
                    if (card == 1 || card == 3) {
                        adapter.clear();
                        adapter.addAll(homeBean.getService_myadd());
                    }
                    // 一键呼叫(车主)
                    if (card == 1) {
                        callAdapter.clear();
                        callAdapter.addAll(homeBean.getService_onkey());
                    }else if(card == 3 || card == 2){
                        List<HomeBean.ServiceDaiwanchengBean> dai = homeBean.getService_daiwancheng();
                        List<HomeBean.ServiceOnKeyBean> KeyBeans = new ArrayList<>();
                        if(dai.size() > 0){
                            HomeBean.ServiceOnKeyBean item = null;
                            for(int i = 0;i< dai.size();i++){
                                item = new HomeBean.ServiceOnKeyBean();
                                item.setServiceid(dai.get(i).getServiceid());
                                item.setSecondname(dai.get(i).getSecondname());
                                item.setPhoto(dai.get(i).getPhoto());
                                item.setServicecategoryname(dai.get(i).getServicecategoryname());
                                item.setState(dai.get(i).getState());
                                item.setRemark(dai.get(i).getRemark());
                                item.setImgs(dai.get(i).getImgs());
                                item.setCreatedate(dai.get(i).getCreatedate());
                                item.setMoney_total(dai.get(i).getMoney_total());
                                item.setDistance(dai.get(i).getDistance());
                                KeyBeans.add(item);
                            }
                        }
                        callAdapter.clear();
                        callAdapter.addAll(KeyBeans);
                    }
                    // 其他的服务(车主)
                    if (card == 1) {
                        serviceAdapter.clear();
                        serviceAdapter.addAll(homeBean.getService_other());
                    }else if(card == 3 || card == 2){
                        List<HomeBean.ServiceDaiqiangdanBean> qiang = homeBean.getService_daiqiangdan();
                        List<HomeBean.ServiceOtherBean> otherBeans = new ArrayList<>();
                        if(qiang.size() > 0){
                            HomeBean.ServiceOtherBean item = null;
                            for(int i = 0;i< qiang.size();i++){
                                item = new HomeBean.ServiceOtherBean();
                                item.setServiceid(qiang.get(i).getServiceid());
                                item.setSecondname(qiang.get(i).getSecondname());
                                item.setPhoto(qiang.get(i).getPhoto());
                                item.setServicecategoryname(qiang.get(i).getServicecategoryname());
                                item.setState(qiang.get(i).getState());
                                item.setRemark(qiang.get(i).getRemark());
                                item.setImgs(qiang.get(i).getImgs());
                                item.setCreatedate(qiang.get(i).getCreatedate());
                                item.setMoney_total(qiang.get(i).getMoney_total());
                                item.setDistance(qiang.get(i).getDistance());
                                otherBeans.add(item);
                            }
                        }
                        serviceAdapter.clear();
                        serviceAdapter.addAll(otherBeans);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == RESULT_OK){
            if(data != null){
                tv_location.setText(data.getStringExtra("city"));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocationUtils.locateDelegateArrayList.remove(this);
        LocationUtils.stopLocation();
    }
}
